package com.bing.services.impl;

import com.bing.Component.Context;
import com.bing.services.CommandService;
import com.bing.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2015/5/31.
 */
public abstract class AbstractCommandService implements CommandService, Ordered {

    protected int order;

    public static final String TW = "@";

    @Autowired
    protected UserService userService;

    protected abstract List<String> getContexts();

    @Override
    public boolean canHandle(Context context) {
        if (!StringUtils.hasText(context.getCommand())) {
            return false;
        }
        for (String s : getContexts()) {
            if (s.equalsIgnoreCase(context.getCommand())) {
                getLogger().info("适配命令:{}, 事件类型:{}, 文本内容:{}", s, context.getRequestMessage().getEvent(), context.getRequestMessage().getContent());
                context.getUser().setCommand(s);
                context.getUser().setLatestActive(new Date());
                if (StringUtils.hasText(context.getRequestMessage().getContent())) {
                    context.getUser().setHistoryCommands(context.getRequestMessage().getContent().trim());
                }
                userService.updateUser(context.getUser());
                return true;
            }
        }
        return false;
    }

    protected abstract org.slf4j.Logger getLogger();

    public void setOrder(int order) {
        this.order = order;
    }

    /**
     * Return the order value of this object, with a
     * higher value meaning greater in terms of sorting.
     * <p>Normally starting with 0, with {@code Integer.MAX_VALUE}
     * indicating the greatest value. Same order values will result
     * in arbitrary positions for the affected objects.
     * <p>Higher values can be interpreted as lower priority. As a
     * consequence, the object with the lowest value has highest priority
     * (somewhat analogous to Servlet "load-on-startup" values).
     *
     * @return the order value
     */
    @Override
    public int getOrder() {
        return this.order;
    }
}
